package com.org.platform.utils.rabbitmq;

import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.util.Date;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @Description
 * @auther dh
 * @date 2022/1/30 21:24
 */
public class Producer {

	public static void main(String[] args) throws Exception {
		String message = "hello当前时间为：" + new Date().toString();
		String changeName = "fanoutExchange";
		Channel channel = getChannel();
		channel.exchangeDeclare(changeName, BuiltinExchangeType.FANOUT, true, false, null);
		channel.queueDeclare("Q1", true, false, false, null);
		channel.queueBind("Q1", changeName, "Q1");
		channel.queueDeclare("Q2", true, false, false, null);
		channel.queueBind("Q2", changeName, "Q2");
		channel.basicPublish(changeName, "", null, message.getBytes());
		channel.close();
		System.out.println("hello world");
	}

	public static ConnectionFactory getConnectionFactory() {
		ConnectionFactory connectionFactory = new ConnectionFactory();
		connectionFactory.setHost("127.0.0.1");
		connectionFactory.setPort(5672);
		connectionFactory.setUsername("devg");
		connectionFactory.setPassword("devg@123");
		connectionFactory.setVirtualHost("dev");
		Integer multiple = 1;
		connectionFactory.setAutomaticRecoveryEnabled(true);
		connectionFactory.setNetworkRecoveryInterval(60000 * multiple);
		connectionFactory.setRequestedHeartbeat(2 * multiple);
		connectionFactory.setConnectionTimeout(60000 * multiple);
		connectionFactory.setHandshakeTimeout(60000 * multiple);
		return connectionFactory;
	}

	public static Channel getChannel() {
		Channel channel = null;
		try {
			int nThreads = 5;
			ExecutorService es = Executors.newFixedThreadPool(nThreads);
			Connection connection = getConnectionFactory().newConnection(es);
			if (connection == null) {
				return null;
			}
			channel = connection.createChannel();
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return channel;
	}


}
